<template>
  <div>
    <div ref="inputBox"
         class="input-box"
         contenteditable
         @keydown.enter.prevent="{}"
         @paste="paste"
         @input="input"
         @blur.prevent="blur"/>
  </div>
</template>

<script>
export default {
  name: "BdsInputBox",
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      _lastRange: null
    }
  },
  mounted() {
    this.insert(this.value)
  },
  watch: {
    value() {
      let inputBox = this.$refs.inputBox
      if (inputBox.innerText === this.value) {
        return
      }
      this.$refs.inputBox.innerText = this.value
    }
  },
  methods: {
    update(value) {
      value = value || this.$refs.inputBox.innerText
      this.$emit('input', value)
    },
    paste(e) {
      e.preventDefault()
      let clipboardData = e.clipboardData
      let text = clipboardData.getData('text/plain')
      if (!text) {
        text = clipboardData.getData('text/html')
      }
      text = text.replace(/[\n\r]/g, '')

      this.blur()
      this.insert(text)
    },
    input() {
      this.update()
    },
    blur() {
      let selection = getSelection();
      this._lastRange = selection.getRangeAt(0);
    },
    insert(text) {
      if (!text) return

      let inputBox = this.$refs.inputBox
      inputBox.focus()

      // 获取选定对象
      let selection = getSelection();
      if (!selection.rangeCount) {
        this.update(this.value + text)
        return
      }

      if (this._lastRange) {
        // 存在最后光标对象，选定对象清除所有光标并添加最后光标还原之前的状态
        selection.removeAllRanges()
        selection.addRange(this._lastRange)
        selection.deleteFromDocument()
      }

      let range = selection.getRangeAt(0);

      let span = document.createElement("span")
      span.innerText = text

      range.insertNode(span.childNodes[0])
      range.collapse(false);
      this._lastRange = range;
      this.update()
    },
  }
}
</script>

<style scoped lang="scss">
.input-box {
  border: 1px solid #ccc;
  height: 100px;
  font-family: Consolas, serif;
  border-radius: 5px;
  padding: 5px 10px;
  overflow-y: auto;
}
</style>
